$(function() {
  // Socket.io connection

  var docUrl = document.URL;

  console.log(docUrl);
  var socket = io.connect(docUrl),
      roomId = '';

  // Join to room
  $('#joinButtonWrap').on('click', 'button', function() {
    roomId = $(this).data('id');
    $('#chat')
      .show()
      .find('h1').html('room' + roomId).end()
      .find('#log').html('');
    socket.emit('join:room', {roomId: roomId});
  });

  // Send a message
  $('#submit').on('click', function() {
    var msg = $('#message').val();
    if(!msg) return;
    socket.emit('send:message', {
      roomId: roomId,
      message: msg
    });
  });
  $('#message').keypress(function(e) {
    if(e.which == 13) {
      $(this).blur();
      $('#submit').focus().click();
      $('#message').text = "";
    }
  });

  // Receive a message
  socket.on('send:message', function(data) {
    $('#chat').find('#log').append('<p>' + data + '</p>');
  });
});

